<template>
  <div class="app-container">
    <div style="display: flex;width: 100%; justify-content: flex-start;">
      <div style="width: 25%; margin-right: 20px;padding-bottom: 10px">
        <div style="padding-bottom: 5px; font-size: 14px; font-weight: bold;">
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            size="small">
          </el-input>
        </div>
        <el-tree ref="deviceRef" :data="deviceOptions" :filter-node-method="filterNode"
                 :props="defaultProps" class="tree-border" icon-class="el-tree-node__expand-icon el-icon-caret-right"
                 style="padding: 10px;height: 600px; overflow: auto"
                 @node-click="handleNodeClick">

          <div slot-scope="{ node, data }" class="custom-tree-node tree-div">
            <span :style="{color:data.online?'#409EFF':'#F56C6C'}" class="tree-item-font"
                  style="width: 30%">{{ node.label }}</span>
            <span class="tree-item-font">{{ data.chargeStationName ? data.chargeStationName : '未绑定' }}</span>
            <span>
              <el-button
                size="mini"
                type="text"
                @click.stop="() => handleGatewayUpdate(data)">
                管理
              </el-button>
            </span>
          </div>
        </el-tree>
      </div>
      <div style="width: 74%; padding-top: 5px;">

        <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px"
                 size="small">
          <el-form-item label="" prop="macid">
            <el-input
              v-model="queryParams.macid"
              clearable
              placeholder="请输入地锁ID"
              style="width: 140px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="gatewayName">
            <el-input
              v-model="queryParams.gatewayName"
              clearable
              placeholder="请输入网关名称"
              style="width: 140px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="arm">
            <el-select
              v-model="queryParams.arm"
              clearable
              placeholder="摇臂状态"
              size="small"
              style="width: 140px">
              <el-option
                v-for="(item,index) in armList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="beep">
            <el-select
              v-model="queryParams.beep"
              clearable
              placeholder="报警状态"
              size="small"
              style="width: 140px">
              <el-option
                v-for="(item,index) in beepList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="online">
            <el-select
              v-model="queryParams.online"
              clearable
              placeholder="在线状态"
              size="small"
              style="width: 140px">
              <el-option
                v-for="(item,index) in onlineList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="parkinglockList" @selection-change="handleSelectionChange">
          <!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column align="center" label="地锁ID" prop="macid"/>
          <el-table-column align="center" label="网关ID" prop="gatewayId" width="150"/>
          <el-table-column align="center" label="网关名称" prop="gatewayName" width="180"></el-table-column>
          <el-table-column align="center" label="序号" prop="parkName" width="150">
            <template v-slot="scope">
              <el-input v-if="rowIndex===scope.$index"
                        style="width: 140px"
                        size="mini"
                        placeholder="请输入内容"
                        v-model.trim="scope.row.parkName">
                <el-button slot="append" icon="el-icon-edit" @click="submitForm(scope.row)"></el-button>
              </el-input>
              <span @click="rowIndex=scope.$index" v-else>
                {{ scope.row.parkName }}
            <i class="el-icon-edit" style="margin-left: 10px"></i>
          </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="摇臂状态" prop="arm">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.arm==='high'"
                v-model="scope.row.visible"
                placement="top"
                trigger="click"
                width="160">
                <p>是否确定降下车位锁吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
                  <el-button size="mini" type="primary"
                             @click="scope.row.visible = false,handleOperateParkinglock(scope.row.macid,'down')">确定
                  </el-button>
                </div>
                <el-button slot='reference' plain type="primary">HIGH</el-button>
              </el-popover>
              <el-popover
                v-else-if="scope.row.arm==='low'"
                v-model="scope.row.visibleLOW"
                placement="top"
                trigger="click"
                width="160">
                <p>是否确定升起车位锁吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="scope.row.visibleLOW = false">取消</el-button>
                  <el-button size="mini" type="primary"
                             @click="scope.row.visibleLOW = false,handleOperateParkinglock(scope.row.macid,'up')">确定
                  </el-button>
                </div>
                <el-button slot='reference' plain type="success">LOW</el-button>
              </el-popover>
              <el-popover
                v-else
                v-model="scope.row.visibleERROR"
                placement="top"
                trigger="click"
                width="160">
                <p>是否确定归位车位锁吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="scope.row.visibleERROR = false">取消</el-button>
                  <el-button size="mini" type="primary"
                             @click="scope.row.visibleERROR = false,handleOperateParkinglock(scope.row.macid,'up')">确定
                  </el-button>
                </div>
                <el-button slot='reference' plain type="danger">ERROR</el-button>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" label="报警器状态" prop="beep">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.beep==='on'"
                v-model="scope.row.visibleON"
                placement="top"
                trigger="click"
                width="160">
                <p>是否关闭鸣响？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="scope.row.visibleON = false">取消</el-button>
                  <el-button size="mini" type="primary"
                             @click="scope.row.visibleON = false,handleBeepCmd(scope.row,'off')">确定
                  </el-button>
                </div>
                <el-button slot='reference' plain type="primary">ON</el-button>
              </el-popover>
              <el-popover
                v-else
                v-model="scope.row.visibleOFF"
                placement="top"
                trigger="click"
                width="180">
                <p>是否开启鸣响？</p>
                <div>
                  <el-input-number v-model="scope.row.sec" :max="255" :min="1"
                                   style="width: 145px;margin-bottom: 10px"></el-input-number>
                </div>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="scope.row.visibleOFF = false">取消</el-button>
                  <el-button size="mini" type="primary"
                             @click="scope.row.visibleOFF = false,handleBeepCmd(scope.row,'on')">确定
                  </el-button>
                </div>
                <el-button slot='reference' plain type="danger">OFF</el-button>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" label="在线状态" prop="online">
            <template slot-scope="scope">
              <el-tag :type="scope.row.online ?'success':'danger'">{{ scope.row.online ? '在线' : '离线' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="异常消息" prop="fauleMsg" show-overflow-tooltip/>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['business:parkinglock:edit']"
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handlePriceUpdate(scope.row)"
              >计费规则
              </el-button>
              <el-button
                v-hasPermi="['business:parkinglock:remove']"
                icon="el-icon-s-platform"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >管理
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :limit.sync="queryParams.pageSize"
          :page.sync="queryParams.pageNum"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 管理车位网关 -->
    <el-dialog :title="gatewayTitle" :visible.sync="gatewayOpen" append-to-body width="400px">
      <el-form ref="gatewayForm" :model="gatewayForm" label-width="80px">
        <el-form-item label="网关名称">
          <div style="display: flex;justify-content: space-between">
            <el-input v-model="gatewayForm.gatewayName" style="width: 60%">
            </el-input>
            <el-button plain type="primary" @click="handleGatewayName">重命名</el-button>
          </div>
        </el-form-item>
        <el-form-item label="挂靠场站">
          <div style="display: flex;justify-content: space-between">
            <div style="width: 70%">
              {{ gatewayForm.chargeStationName ? gatewayForm.chargeStationName : '未绑定' }}
            </div>
            <el-button plain type="primary" @click="handleGatewayName">绑定</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div style="padding-bottom: 10px">
        <el-input
          v-model="filterMapText"
          placeholder="输入关键字进行过滤">
        </el-input>
        <el-tree ref="deviceMapRef" :data="listMap" :filter-node-method="filterListNode"
                 :props="listMapProps" class="tree-border" icon-class="el-tree-node__expand-icon el-icon-caret-right"
                 style="padding: 10px;height: 480px; overflow: auto"
                 @node-click="handleNodeMapClick"></el-tree>
      </div>
    </el-dialog>
    <!-- 添加或修改车位锁管理对话框 -->
    <el-dialog :title="priceTitle" :visible.sync="priceOpen" append-to-body width="600px">
        <el-descriptions :column="3" border class="margin-top" >
          <el-descriptions-item>
            <template slot="label">
              在线状态
            </template>
            {{ form.online ? '在线' : '离线' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              摇臂状态
            </template>
            {{ form.arm === 'high' ? '升起' : form.arm === 'low' ? '降下' : '报错' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              报警器状态
            </template>
            {{ form.beep === 'on' ? '开启' : '关闭' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              地磁自检
            </template>
            {{ form.mag }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              在位检测
            </template>
            {{ form.ultrrv }}
          </el-descriptions-item>
          <!--         <el-descriptions-item>
                     <template slot="label">
                       最后一次执行结果
                     </template>
                     {{form.ret}}
                   </el-descriptions-item>-->
          <el-descriptions-item>
            <template slot="label">
              异常信息
            </template>
            {{ form.fauleMsg }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              信号
            </template>
            {{ form.rssi }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              动力电压
            </template>
            {{ form.voltage }}
          </el-descriptions-item>
          fwVersion
          <el-descriptions-item>
            <template slot="label">
              硬件版本
            </template>
            {{ form.fwVersion }}
          </el-descriptions-item>
        </el-descriptions>
      <el-form ref="form" label-position="left" :model="form" :rules="rules" label-width="100px" style="margin-top: 10px">
        <el-form-item label="计费规则" prop="masterPwd">
          <el-select v-model="form.priceId" placeholder="请选择">
            <el-option
              v-for="item in priceList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePriceForm" >确 定</el-button>
        <el-button @click="cancel('priceOpen')">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改车位锁管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="900px">
      <div style="display: flex;justify-content: space-between">
        <el-descriptions :column="1" border class="margin-top" style="width: 45%" title="占位锁实况">
          <template slot="extra">
            <el-button size="small" type="primary" @click="getParkStatus">同步状态</el-button>
          </template>
          <el-descriptions-item>
            <template slot="label">
              地锁ID
            </template>
            {{ form.macid }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              网关ID
            </template>
            {{ form.gatewayId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              网关名称
            </template>
            {{ form.gatewayName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              在线状态
            </template>
            {{ form.online ? '在线' : '离线' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              摇臂状态
            </template>
            {{ form.arm === 'high' ? '升起' : form.arm === 'low' ? '降下' : '报错' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              报警器状态
            </template>
            {{ form.beep === 'on' ? '开启' : '关闭' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              地磁自检
            </template>
            {{ form.mag }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              在位检测
            </template>
            {{ form.ultrrv }}
          </el-descriptions-item>
          <!--         <el-descriptions-item>
                     <template slot="label">
                       最后一次执行结果
                     </template>
                     {{form.ret}}
                   </el-descriptions-item>-->
          <el-descriptions-item>
            <template slot="label">
              异常信息
            </template>
            {{ form.fauleMsg }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              信号
            </template>
            {{ form.rssi }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              动力电压
            </template>
            {{ form.voltage }}
          </el-descriptions-item>
          fwVersion
          <el-descriptions-item>
            <template slot="label">
              硬件版本
            </template>
            {{ form.fwVersion }}
          </el-descriptions-item>
        </el-descriptions>
        <div style="width: 45%" v-loading="xxLodading">
          <div
            style="height: 32px;margin-bottom: 20px;display: flex;justify-content: space-between;align-items: center">
            <span style="font-size: 16px;font-weight: bold;">功能设置</span>
            <el-button size="small" type="primary" @click="getParkParam">同步设置</el-button>
          </div>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="主人密码" prop="masterPwd">
              <el-input v-model="form.masterPwd" placeholder="请输入主人密码">
                <el-button slot="append" @click="handlePwd('master_pwd',form.masterPwd)"> 设置</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="客人密码" prop="guestPwd">
              <el-input v-model="form.guestPwd" placeholder="请输入客人密码">
                <el-button slot="append" @click="handlePwd('guest_pwd',form.guestPwd)"> 设置</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="蓝牙名称" prop="bleName">
              <el-input v-model="form.bleName" placeholder="请输入蓝牙名称">
                <el-button slot="append" @click="handleBle('ble_name',form.bleName)"> 设置</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="地锁使能" prop="lockEnable">
              <el-switch
                v-model="form.lockEnable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChange($event,'lock_en','lockEnable')">
              </el-switch>
              <!--             <el-input v-model="form.lockEnable" placeholder="请输入地锁使能" />-->
            </el-form-item>
            <el-form-item label="报警器使能" prop="beepEnable">
              <el-switch
                v-model="form.beepEnable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChange($event,'beep_en','beepEnable')">
              </el-switch>
              <!--             <el-input v-model="form.beepEnable" placeholder="请输入报警器使能" />-->
            </el-form-item>
            <el-form-item label="驶离功能" prop="detectEnable">
              <el-switch
                v-model="form.detectEnable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChange($event,'detect_en','detectEnable')">
              </el-switch>
              <!--             <el-input v-model="form.detectEnable" placeholder="请输入驶离功能" />-->
            </el-form-item>
            <el-form-item label="马达过载功能" prop="overloadEnable">
              <el-switch
                v-model="form.overloadEnable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChange($event,'overload_en','overloadEnable')">
              </el-switch>
              <!--             <el-input v-model="form.overloadEnable" placeholder="请输入马达过载功能" />-->
            </el-form-item>
            <el-form-item label="手动上锁功能" prop="manualLockEnable">
              <el-switch
                v-model="form.manualLockEnable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChange($event,'manual_lock_en','manualLockEnable')">
              </el-switch>
              <!--             <el-input v-model="form.manualLockEnable" placeholder="请输入手动上锁功能" />-->
            </el-form-item>
            <el-form-item label="手动解锁功能" prop="manualUnLockEnable">
              <el-switch
                v-model="form.manualUnLockEnable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleChange($event,'manual_unlock_en','manualUnLockEnable')">
              </el-switch>
              <!--             <el-input v-model="form.manualUnLockEnable" placeholder="请输入手动解锁功能" />-->
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listParkinglock,
  getParkinglock,
  delParkinglock,
  addParkinglock,
  updateParkinglock, operateParkinglock, beepCmd, setParkParam, getParkParam, getParkStatus
} from "@/api/business/parkinglock";
import {getGateway, listGateway, updateGateway} from "@/api/business/gateway";
import {listPriceAll} from "@/api/business/price";
import mqtt from 'mqtt'

const armList = [
  {
    value: 'high',
    label: '开锁'
  },
  {
    value: 'low',
    label: '降锁'
  },
  {
    value: 'error',
    label: '归位'
  }
]

const beepList = [
  {
    value: 'on',
    label: '开启'
  },
  {
    value: 'off',
    label: '关闭'
  }
]

const onlineList = [
  {
    value: 'true',
    label: '在线'
  },
  {
    value: 'false',
    label: '离线'
  }
]
export default {
  name: "Parkinglock",
  data() {
    return {
      armList,
      beepList,
      onlineList,
      rowIndex: null,
      xxLodading: false,
      visible: false,
      size: 0,
      deviceOptions: [],
      defaultProps: {
        children: 'children',
        label: 'gatewayName'
      },
      listMapProps: {
        children: 'children',
        label: 'label'
      },
      filterText: '',
      filterMapText: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车位锁管理表格数据
      parkinglockList: [],
      // 弹出层标题
      title: "",
      gatewayTitle: "",
      priceTitle: "",
      // 是否显示弹出层
      open: false,
      gatewayOpen: false,
      priceOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        macid: null,
        gatewayName: null,
        arm: null,
        beep: null,
        beepEnable: null,
        bleName: null,
        chargePort: null,
        chargeStationId: null,
        detectEnable: null,
        deviceId: null,
        deviceName: null,
        fauleMsg: null,
        faultCode: null,
        fwVersion: null,
        gatewayId: null,
        guestPwd: null,
        lastUpdateTime: null,
        lcokEnable: null,
        mag: null,
        manualLockEnable: null,
        manualUnLockEnable: null,
        masterPwd: null,
        online: null,
        opcode: null,
        overloadEnable: null,
        parkName: null,
        priceId: null,
        ret: null,
        rssi: null,
        ultrrv: null,
        voltage: null
      },
      // 表单参数
      form: {},
      gatewayForm: {},
      // 表单校验
      rules: {},
      priceList:[],
      listMap: [],
      receiveNews: '',
      connection: {
        host: '192.168.10.16',
        port: 8083,
        endpoint: '/mqtt',
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // 认证信息
        clientId: 'web_'+Math.floor(Math.random() * 100000),
        username: 'admin',
        password: 'admin123',
      },
      subscription: {
        topic: 'Thubder/charge/wave',
        qos: 0,
      },
      publish: {
        topic: 'PIPELock/status/#',
        qos: 0,
        payload: '{ "msg": "Hello, I am browser." }',
      },
      client: {
        connected: false,
      },
      subscribeSuccess: false,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.deviceRef.filter(val);
    },
    filterMapText(val) {
      this.$refs.deviceMapRef.filter(val);
    },
  },
  created() {
    this.getList();
    this.getGatewayList()
    //this.createConnection()
    //this.doSubscribe()
  },
  methods: {
    // 创建连接
    createConnection() {
      // 连接字符串, 通过协议指定使用的连接方式
      // ws 未加密 WebSocket 连接
      // wss 加密 WebSocket 连接
      // mqtt 未加密 TCP 连接
      // mqtts 加密 TCP 连接
      // wxs 微信小程序连接
      // alis 支付宝小程序连接
      const { host, port, endpoint, ...options } = this.connection
      const connectUrl = `ws://${host}:${port}${endpoint}`
      try {
        this.client = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('mqtt.connect error', error)
      }
      this.client.on('connect', () => {
        console.log('Connection succeeded!')
      })
      this.client.on('error', error => {
        console.log('Connection failed', error)
      })
      this.client.on('message', (topic, message) => {
        this.receiveNews = this.receiveNews.concat(message)
        console.log(`Received message ${message} from topic ${topic}`)
      })
    },
    //订阅主题
    doSubscribe() {
      const { topic, qos } = this.subscription
      this.client.subscribe(topic, qos, (error, res) => {
        if (error) {
          console.log('Subscribe to topics error', error)
          return
        }
        this.subscribeSuccess = true
        console.log('Subscribe to topics res', res)
      })
    },
    async getListPriceAll(){
      try {
        let res = await listPriceAll()
        this.priceList = res.rows
      }catch (e) {

      }
    },
    async getParkStatus() {
      try {
        let res = getParkStatus(this.form.macid)
      } catch (e) {

      }
    },
    async getParkParam() {
      try {
        let res = getParkParam(this.form.macid)
      } catch (e) {

      }
    },
    async handleChange(value, val, before) {
      try {
        await this.updateParkParam(this.form.macid, val, value)
      } catch (e) {
        this.form[before] = !value
      }
    },
    handleBle(option, value) {
      let regex = /^[A-Z][A-Za-z0-9]{5}$/;
      if (!(regex.test(value))) {
        this.$modal.msgError("大写英文字符开头,总共6位");
        return false
      }
      this.updateParkParam(this.form.macid, option, value)
    },
    handlePwd(option, value) {
      if (!(/\d{6}/.test(value))) {
        this.$modal.msgError("密码为6位数字");
        return false
      }
      this.updateParkParam(this.form.macid, option, value)
    },
    async updateParkParam(macid, option, value) {
      try {
        this.xxLodading = true
        let res = await setParkParam(macid, option, value)
        this.xxLodading = false
        this.$modal.msgSuccess('指令发送成功')
      } catch (e) {
        this.xxLodading = false
        return Promise.reject(e)
      }
    },
    handleListMap(data) {
      const treeData = [];

      data.forEach(item => {
        const key = Object.keys(item)[0]; // 获取省份名称
        const stations = item[key]; // 获取充电站列表

        const province = {
          label: key,
          children: []
        };

        stations.forEach(station => {
          province.children.push({
            label: station.stationName,
            id: station.id
          });
        });

        treeData.push(province);
      });
      console.log(treeData)
      this.listMap = treeData
    },
    async handleGatewayName() {
      try {
        let res = await updateGateway(this.gatewayForm)
        this.$modal.msgSuccess("修改成功");
        await this.getGatewayList();
        await this.getList()
      } catch (e) {

      }
    },
    /** 修改按钮操作 */
    handleGatewayUpdate(row) {
      const gatewayId = row.gatewayId
      getGateway(gatewayId).then(response => {
        this.gatewayForm = response.data.parkingLockGateway
        this.handleListMap(response.data.listMap)
        this.gatewayOpen = true;
        this.gatewayTitle = "占位锁网关管理";
      });
    },
    async handleBeepCmd(data, type) {
      try {
        this.loading = true
        let res = await beepCmd(data.macid, type, data.sec)
        this.getList();
      } catch (e) {
        this.loading = false
      }
    },
    async handleOperateParkinglock(macid, type) {
      try {
        this.loading = true
        let res = await operateParkinglock(macid, type)
        if (res.data.subscribeMsg) {
          this.$modal.msgSuccess('指令发送成功')
        } else {
          this.$modal.msgError("指令发送失败");
        }
        this.getList();
      } catch (e) {
        this.loading = false
      }
    },
    handleNodeClick(a, b, c) {
      this.queryParams.gatewayId = a.gatewayId
      this.getList();
    },
    handleNodeMapClick(a, b, c) {
      if (a.id) {
        this.gatewayForm.chargeStationId = a.id
        this.gatewayForm.chargeStationName = a.label
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.gatewayName.indexOf(value) !== -1;
    },
    filterListNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询网关列表 **/
    async getGatewayList() {
      try {
        let res = await listGateway()
        this.deviceOptions = res.rows
      } catch (e) {
      }
    },
    /** 查询车位锁管理列表 */
    getList() {
      this.loading = true;
      listParkinglock(this.queryParams).then(response => {
        this.parkinglockList = response.rows;
        this.total = response.total;
        this.parkinglockList.forEach(item => {
          this.$set(item, 'visible', false)
          this.$set(item, 'visibleLOW', false)
          this.$set(item, 'visibleERROR', false)
          this.$set(item, 'visibleON', false)
          this.$set(item, 'visibleOFF', false)
          this.$set(item, 'sec', 255)
        })
        this.loading = false;
      });
    },
    // 取消按钮
    cancel(val) {
      this[val] = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        macid: null,
        arm: null,
        beep: null,
        lockEnable: null,
        beepEnable: null,
        bleName: null,
        chargePort: null,
        chargeStationId: null,
        createTime: null,
        detectEnable: null,
        deviceId: null,
        deviceName: null,
        fauleMsg: null,
        faultCode: null,
        fwVersion: null,
        gatewayId: null,
        guestPwd: null,
        lastUpdateTime: null,
        lcokEnable: null,
        mag: null,
        manualLockEnable: null,
        manualUnLockEnable: null,
        masterPwd: null,
        online: null,
        opcode: null,
        overloadEnable: null,
        parkName: null,
        priceId: null,
        ret: null,
        rssi: null,
        ultrrv: null,
        updateBy: null,
        voltage: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.gatewayId = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.macid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车位锁管理";
    },
    /** 修改按钮操作 */
    handlePriceUpdate(row) {
      this.reset();
      const macid = row.macid || this.ids
      getParkinglock(macid).then(response => {
        this.form = response.data;
        this.getListPriceAll()
        this.priceOpen = true;
        this.priceTitle = "绑定计费规则";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const macid = row.macid || this.ids
      getParkinglock(macid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车位锁管理";
      });
    },
    handlePriceForm() {
      updateParkinglock(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.priceOpen = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm(data) {
      if (!/^\d*$/.test(data.parkName)) {
        this.$modal.msgError('请输入数字')
        return
      }
      updateParkinglock(data).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.rowIndex = null
        this.getList();
      });
      /*this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.macid != null) {
            updateParkinglock(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addParkinglock(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });*/
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const macids = row.macid || this.ids;
      this.$modal.confirm('是否确认删除车位锁管理编号为"' + macids + '"的数据项？').then(function () {
        return delParkinglock(macids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/parkinglock/export', {
        ...this.queryParams
      }, `parkinglock_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.tree-div {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  .tree-item-font {
    font-size: 12px;
  }
}
</style>
